package com.ruoyi.framework.config;


import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 定时任务
 * @author Administrator
 */
@Component
@Configuration
@EnableScheduling
public class CrontabConfig {

    private static final Logger log = LoggerFactory.getLogger(CrontabConfig.class);

    @Value("${crontab.syncDeptJob}")
    private String syncDeptJob;

    @Value("${crontab.syncUserJob}")
    private String syncUserJob;

    @Value("${crontab.cleanJob}")
    private String cleanJob;

    @Resource
    private ISysUserService userService;

    @Resource
    private ISyncSysUserService iSyncSysUserService;

    @Resource
    private ISyncSysDeptService iSyncSysDeptService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private IWorkItemOaService iWorkItemOaService;

    @Resource
    private IWorkItemHrService iWorkItemHrService;

    @Resource
    private IWorkItemBpmService iWorkItemBpmService;

    @Resource
    private IWorkItemPendService iWorkItemPendService;


    @Resource
    private IUnifyUserInfoService iUnifyUserInfoService;

    @Resource
    private ISyncDataLogService iSyncDataLogService;

    @Scheduled( cron= "${crontab.syncUserJob}")
    public void cronSyncUser(){
        SyncSysUser syncSysUser = new SyncSysUser();
        syncSysUser.setSyncFlag("0");
        syncUser(syncSysUser);
        log.info("同步用户任务,定时表达式：{} " ,syncUserJob);
    }

    @Scheduled( cron= "${crontab.syncDeptJob}")
    public void cronSyncDept(){
        SyncSysDept syncSysDept = new SyncSysDept();
        syncSysDept.setSyncFlag("0");
        syncDept(syncSysDept);
        log.info("同步部门任务,定时表达式：{}" ,syncDeptJob);
    }

    @Scheduled(cron = "${crontab.syncOaPend}")
    public void cronSyncOaPend() {
        iWorkItemOaService.syncWorkItemOa("定时任务");
    }

    @Scheduled(cron = "${crontab.syncOaPend}")
    public void cronSyncBpmPend() {
        iWorkItemBpmService.syncWorkItemBpm("定时任务");
    }

    @Scheduled(cron = "${crontab.syncOaPend}")
    public void cronSyncHrPend() {
        iWorkItemHrService.syncWorkItemHr("定时任务");
    }

    @Scheduled( cron= "${crontab.cleanJob}")
    public void authUserDataClean (){
        closeForceStatus();
        closeUserAccount();
        resigningStatus();
        getTimingStatus();
        log.info("状态值清理任务,定时表达式：{}" ,cleanJob);
    }

    @Scheduled( cron= "${crontab.initUnifyUser}")
    public void initUnifyUserData (){
        SyncDataLog syncDataLog = new SyncDataLog();
        syncDataLog.setType("1");
        int i = iSyncDataLogService.selectCountSyncDataLogToday(syncDataLog);
        if (i == 0) {
            iUnifyUserInfoService.initUnifyUserInfo("定时任务");
            log.info("统一用户查询初始化任务已执行,定时表达式：{}", cleanJob);
        }else {
            log.info("统一用户查询初始化任务今天已执行,当前未执行,定时表达式：{}", cleanJob);
        }

    }

    public void syncUser (SyncSysUser syncSysUser){
        List<SyncSysUser> syncSysUsers = iSyncSysUserService.selectSyncSysUserList(syncSysUser);
        log.info("开始执行本次同步用户任务 同步数据有：{} 条",syncSysUsers.size());
        if (syncSysUsers.size() == 0) {
            return;
        }
        for (int i = 0; i < syncSysUsers.size(); i++) {
            try {
                SysUser sysUser = convertUserValue(syncSysUsers.get(i));
                sysUser.setCreateBy("admin");
                SysUser sysUserByUserId = userService.checkUserIdCodeUnique(sysUser.getUserIdCode());
                if (null != sysUserByUserId && null != sysUserByUserId.getId()) {

                    if (!"1".equals(sysUserByUserId.getAccountStatus())) {
                        sysUser.setPhonenumber(null);
                    }
                    log.info("工号为：{} ,  用户状态为：{} ,全局用户id：{}", sysUserByUserId.getUserNo(), sysUserByUserId.getAccountStatus(),sysUser.getUserIdCode());
                    sysUser.setId(sysUserByUserId.getId());
                    userMapper.updateUser(sysUser);
                    userService.initUserAccountStatus(sysUser);

                } else {
                    sysUser.setPassword(SecurityUtils.encryptPassword("#*123*789*#"));
                    Long[] roles = new Long[]{2L};
                    sysUser.setRoleIds(roles);
                    userService.insertUser(sysUser);
                }
                syncSysUser.setSyncFlag("1");
                //离职时间未判空更新，所以需要确定的传值
                syncSysUser.setEmpQuitDate(sysUser.getQuitDate());
                syncSysUser.setEmpId(sysUser.getUserIdCode());
                syncSysUser.setUserStatus(null);
                iSyncSysUserService.updateSyncSysUser(syncSysUser);
            } catch (Exception e) {
                log.error("同步用户任务,报错信息 {} ", e.getMessage());
                e.printStackTrace();
            }
        }
    }


    public void syncDept (SyncSysDept syncSysDept){
        List<SyncSysDept> syncSysDepts = iSyncSysDeptService.selectSyncSysDeptList(syncSysDept);
        log.info("开始执行本次同步部门任务 同步数据有：{} 条",syncSysDepts.size());
        if (syncSysDepts.size() == 0) {
            return;
        }
        for (int i = 0; i < syncSysDepts.size(); i++) {

            try {
                SyncSysDept oneSyncSysDept = syncSysDepts.get(i);
                SysDept sysDept = convertDeptValue(oneSyncSysDept);
                sysDept.setCreateBy("admin");
                SysDept sysDeptSource = deptService.selectDeptByIdCode(sysDept.getDeptIdCode());
                log.info("开始同步部门数据,部门全局id为：{}",sysDept.getDeptIdCode());
                if (sysDeptSource != null) {
                    deptService.updateDept(sysDept);
                } else {
                    deptService.insertDeptByOne(sysDept);
                }
                String flag = oneSyncSysDept.getFlag();
                syncSysDept.setSyncFlag("1");
                syncSysDept.setDeptId(sysDept.getDeptIdCode());
                iSyncSysDeptService.updateSyncSysDept(syncSysDept);
                if ("2".equals(flag)){
                    log.info("开始删除部门数据,部门全局id为：{}",sysDept.getDeptIdCode());
                    deptService.deleteDeptByIdCode(sysDept.getDeptIdCode());
                    iSyncSysDeptService.deleteSyncSysDeptById(oneSyncSysDept.getId());
                }

            } catch (Exception e) {
                log.error("同步部门任务,报错信息 {} ", e.getMessage());
                e.printStackTrace();
            }
        }
    }


    private void closeUserAccount(){
        userService.updateCloseUserAccount();
    }

    private void closeForceStatus(){
        userService.updateUserForceFlag();

    }

    private void resigningStatus(){
        userService.resigningStatus();

    }

    private void getTimingStatus (){
        userService.userStatusLinkage();
    }



    private SysUser convertUserValue(SyncSysUser syncSysUser) {
        SysUser sysUser = new SysUser();
        // 员工全局ID
        String empId = syncSysUser.getEmpId();
        //HR中员工ID
        Object empIdCode = syncSysUser.getEmpIdCode();
        //员工编号
        Object empNumber = syncSysUser.getEmpNumber();
        //员工名称
        Object empName = syncSysUser.getEmpName();
        // 部门编号
        Object deptId = syncSysUser.getDeptId();
        //HR部门ID
        Object deptIdCode = syncSysUser.getDeptIdCode();
        //员工移动电话号
        Object empMobilePhone = syncSysUser.getEmpMobilePhone();
        //hr的项目负责人编号
        Object empProjectLeader = syncSysUser.getEmpProjectLeader();
        //hr的项目领款经办人编号
        Object empProjectPayee = syncSysUser.getEmpProjectPayee();
        //是否项目负责人
        Object empJudgeProjectLeader = syncSysUser.getEmpJudgeProjectLeader();
        //是否项目领款经办人
        Object empJudgeProjectPayee = syncSysUser.getEmpJudgeProjectPayee();
        //在职状态编码
        Object empIncumbencyState = syncSysUser.getEmpIncumbencyState();
        //项目负责人全局ID
        Object empProjectLeaderId = syncSysUser.getEmpProjectLeaderId();
        //领款经办人全局ID
        Object empProjectPayeeId = syncSysUser.getEmpProjectPayeeId();
        //性别
        Object empSex = syncSysUser.getEmpSex();
        //主职
        Object partType = syncSysUser.getPartType();
        //证件号码
        Object empIdNumber = syncSysUser.getEmpIdNumber();
        //证件类型
        Object idTypeContent = syncSysUser.getIdTypeContent();
        //主管单位名称
        Object competentOrgContent = syncSysUser.getCompetentOrgContent();
        //在职状态
        Object incumbencyContent = syncSysUser.getIncumbencyContent();
        //员工编号有效性
        Object empNumberEffectiveness = syncSysUser.getEmpNumberEffectiveness();
        //员工编号有效性
        Object empIsValidContent = syncSysUser.getEmpIsvalidContent();
        //公司邮箱
        Object empCompanyEmail = syncSysUser.getEmpCompanyEmail();
        //人员类别ID
        Object empPersonnelType = syncSysUser.getEmpPersonnelType();
        //人员类别
        Object personTypeContent = syncSysUser.getPersonTypeContent();
        //入职日期
        Date empEntryDate = syncSysUser.getEmpEntryDate();
        //离职日期
        Date empQuitDate = syncSysUser.getEmpQuitDate();
        //人事资料有效期
        Date empDataValid = syncSysUser.getEmpDataValid();
        //TJEC在职状态编码
        Object incumbencyStateTjec = syncSysUser.getEmpIncumbencyStateTjec();
        //TJEC人员类别ID
        Object personnelTypeTjec = syncSysUser.getEmpPersonnelTypeTjec();

        sysUser.setDataValid(empDataValid);
        sysUser.setEntryDate(empEntryDate);
        sysUser.setQuitDate(empQuitDate);
        sysUser.setUserId(null == empIdCode ? null : empIdCode.toString());
        sysUser.setUserName(null == empNumber ? null : empNumber.toString());
        sysUser.setDeptId(null == deptIdCode ? null : deptIdCode.toString());
        sysUser.setCompetentOrg(null == competentOrgContent ? null : competentOrgContent.toString());
        sysUser.setDeptIdCode(null == deptId ? null : deptId.toString());
        sysUser.setEmail(null == empCompanyEmail ? null : empCompanyEmail.toString());
        sysUser.setUserIdCode(null == empId ? null : empId.toString());
        sysUser.setUserNo(null == empNumber ? null : empNumber.toString());
        sysUser.setNickName(null == empName ? null : empName.toString());
        sysUser.setPhonenumber(null == empMobilePhone ? null : empMobilePhone.toString());
        sysUser.setProjectLeader(null == empProjectLeader ? null : empProjectLeader.toString());
        sysUser.setProjectPayee(null == empProjectPayee ? null : empProjectPayee.toString());
        sysUser.setJudgeProjectLeader(null == empJudgeProjectLeader ? null : empJudgeProjectLeader.toString());
        sysUser.setJudgeProjectPayee(null == empJudgeProjectPayee ? null : empJudgeProjectPayee.toString());
        sysUser.setIncumbencyState(null == empIncumbencyState ? null : empIncumbencyState.toString());
        sysUser.setProjectLeaderId(null == empProjectLeaderId ? null : empProjectLeaderId.toString());
        sysUser.setProjectPayeeId(null == empProjectPayeeId ? null : empProjectPayeeId.toString());
        sysUser.setSex(null == empSex?null:empSex.toString());
        sysUser.setPartType(null==partType? null:partType.toString());
        sysUser.setIdNum(null==empIdNumber?null:empIdNumber.toString());
        sysUser.setTypeContent(null==idTypeContent?null:idTypeContent.toString());
        sysUser.setIncumbencyContent(null==incumbencyContent?null:incumbencyContent.toString());
        sysUser.setNumberEffectiveness(null==empNumberEffectiveness?null:empNumberEffectiveness.toString());
        sysUser.setIsvalidContent(null==empIsValidContent?null:empIsValidContent.toString());
        sysUser.setPersonnelType(null==empPersonnelType?null:empPersonnelType.toString());
        sysUser.setPersonTypeContent(null==personTypeContent?null:personTypeContent.toString());
        sysUser.setIncumbencyStateTjec(null==incumbencyStateTjec?null:incumbencyStateTjec.toString());
        sysUser.setPersonnelTypeTjec(null==personnelTypeTjec?null:personnelTypeTjec.toString());
        return sysUser;
    }


    private UnifyUserInfo convertUnifyUserValue(Map unifyMap) {
        UnifyUserInfo unifyUserInfo = new UnifyUserInfo();
        // 员工全局ID
        Object empId = unifyMap.get("");
//        unifyUserInfo.setAccountNo();
        return unifyUserInfo;
    }

    private SysDept convertDeptValue(SyncSysDept syncSysDept) {
        SysDept sysDept = new SysDept();
        //部门全局ID
        Object deptId = syncSysDept.getDeptId();
        //父级部门全局ID
        Object deptParentId = syncSysDept.getDeptParentId();
        //部门名称
        Object deptContent = syncSysDept.getDeptContent();
        //HR部门代码
        Object deptCode = syncSysDept.getDeptCode();
        //部门全称
        Object deptAllContent = syncSysDept.getDeptAllContent();
        //部门层数
        Object deptGrade = syncSysDept.getDeptGrade();
        //父级部门HR代码
        Object deptParentCode = syncSysDept.getDeptParentCode();
        //分管领导HR代码
        Object deptInchargeLeader = syncSysDept.getDeptInchargeLeader();
        //部门领导HR代码
        Object deptLeader = syncSysDept.getDeptLeader();
        //OA组织编码
        Object deptOaOrgCode = syncSysDept.getDeptOaOrgCode();
        //HR部门ID
        Object deptIdCode = syncSysDept.getDeptIdCode();
        //父级HR部门ID
        Object deptParentIdCode = syncSysDept.getDeptParentIdCode();
        //排序code
        Object deptOrderCode = syncSysDept.getDeptOrderCode();
        //删除标志（0代表存在 2代表删除）
        Object deptDeleted = syncSysDept.getDeptDeleted();
        //部门类型
        Object deptType = syncSysDept.getDeptType();
        //末级标志
        Object deptEndMark = syncSysDept.getDeptEndMark();
        //分管领导全局ID
        Object deptInchargeLeaderId = syncSysDept.getDeptInchargeLeaderId();
        //主管领导全局ID
        Object deptLeaderId = syncSysDept.getDeptLeaderId();

        sysDept.setDeptId(null == deptIdCode ? null : Long.parseLong(deptIdCode.toString()) );
        sysDept.setParentId(null == deptParentIdCode ? null : Long.parseLong(deptParentIdCode.toString()));
        sysDept.setDeptName(null == deptContent ? null : deptContent.toString());
        sysDept.setDeptCode(null == deptCode ? null : deptCode.toString());
        sysDept.setDelFlag(null == deptDeleted ? null : deptDeleted.toString());
        sysDept.setDeptIdCode(null == deptId ? null : deptId.toString());
        sysDept.setDeptParentIdCode(null == deptParentId ? null : deptParentId.toString());
        sysDept.setDeptGrade(null == deptGrade ? null : Integer.parseInt(deptGrade.toString()));
        sysDept.setDeptAllContent(null == deptAllContent ? null : deptAllContent.toString());
        sysDept.setDeptParentCode(null == deptParentCode ? null : deptParentCode.toString());
        sysDept.setDeptInchargeLeader(null == deptInchargeLeader ? null : deptInchargeLeader.toString());
        sysDept.setDeptLeader(null == deptLeader ? null : deptLeader.toString());
        sysDept.setDeptOaOrgCode(null == deptOaOrgCode ? null : deptOaOrgCode.toString());
        sysDept.setOrderNum(null == deptOrderCode ? null : deptOrderCode.toString());
        sysDept.setDeptType(null == deptType ? null : deptType.toString());
        sysDept.setDeptEndMark(null == deptEndMark ? null : deptEndMark.toString());
        sysDept.setDeptInchargeLeaderId(null == deptInchargeLeaderId ? null : deptInchargeLeaderId.toString());
        sysDept.setDeptLeaderId(null == deptLeaderId ? null : deptLeaderId.toString());
        return sysDept;
    }

}
